package com.itheima.reggie.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", value = "/*")
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        log.info("拦截了");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/user/login",
                "/user/sendMsg",
                "/front/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"

        };

        boolean check = check(urls, requestURI);
        if (check) {
            //对资源和登录退出页面放行
            chain.doFilter(request, response);
            return;
        }

        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
            //对已登录的用户进行放行
            //如果登录，将当前登录用户放入ThreadLocal中保存，以供自动填充时，插入字段“updateUser”
            BaseContext.setThreadLocal(employee.getId());
//            log.info(BaseContext.setThreadLocal(employee.getId()));
            chain.doFilter(request, response);
            return;
        }
        UserDto user = (UserDto) request.getSession().getAttribute("user");
        if (user!=null){
            BaseContext.setThreadLocal(user.getId());
            chain.doFilter(request, response);
            return;
        }
        //此时：要拦截且未登录，就会让前端跳转到登录页面
        ObjectMapper objectMapper = new ObjectMapper();
        R<String> notlogin = R.error("NOTLOGIN");
        String s = objectMapper.writeValueAsString(notlogin);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(s);
    }

    @Override
    public void destroy() {

    }

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
